package com.sunjy.common.utils.sms;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangshuai on 2017/11/27.
 */
public class SmsUtils {

    // 获取时间戳  ： sig 和 auth的时间戳保持一致
    public  static  String getTimeStamp(){
        Date date= new Date();
        SimpleDateFormat sf =new SimpleDateFormat("yyyyMMddHHmmss");
        return sf.format(date);
    }
    //创建sig
    public  static  String  createSig(String accountId ,String token ,String time) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        StringBuilder builder =new StringBuilder(accountId);
        builder.append(token);
        builder.append(time);
        EncryptUtil en =new EncryptUtil();
        return en.md5Digest(builder.toString());
    }
    //创建url
    public static  String createUrl(String baseUrl ,String accoutId,String func ,String funconfig, String sig){
        StringBuilder builder =new StringBuilder(baseUrl);
        builder.append("/Accounts/").append(accoutId).append("/").append(func).append("/").append(funconfig).append("?sig=").append(sig);
        String url =builder.toString();
        return url;
    }

    //创建响应头参数
    public static  Map<String ,String> createHeader( String auth){
        Map<String ,String> header=new HashMap<>();
        header.put("Authorization" ,auth);
        return header;
    }
    //创建请求头参数
    public static  String createAuthorization(String accountId ,String time) throws UnsupportedEncodingException {
        String auth=accountId+":"+time;
        auth=base64Encoder(auth);
        return  auth;


    }
    //创建请求体参数
    public static  String createRequestBody(String accountId ,String time){

        return null;
    }

    public static String base64Decoder(String dest)
            throws NoSuchAlgorithmException, IOException
    {
        BASE64Decoder decoder = new BASE64Decoder();
        return new String(decoder.decodeBuffer(dest), "utf-8");
    }

    public static String base64Encoder(String src) throws UnsupportedEncodingException
    {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(src.getBytes("utf-8"));
    }
}
